<?php
namespace Qgs\Controller;
use Think\Model;

/**
 * 普通运费模板
 * Class DlytmpController
 * @package Qgs\Controller
 */
class FreightController extends BaseController {

    /**
     * 普通运费模板
     */
    public function dlytmp(){

        $local_id = session('userInfo')['local_id'];

        $dlytmplist = M('b2c_dlytmplist a')
            ->join(C('DB_PREFIX').'b2c_dlytmp b on a.tmp_id=b.tmp_id')
            ->field('a.*,b.active')
            ->where(['a.local_id' => $local_id, 'b.is_def'=>'1'])
            ->select();
        $this->assign(['dlytmplist' => $dlytmplist]);
        $this->display();
    }

    /**
     * 新增普通运费模板
     */
    public function dlytmpAdd(){
        $local_id = session('userInfo')['local_id'];
        if ($_POST) {

            $type_id = I('type_id', '', htmlspecialchars());
            $type_name = I('type_name', '', htmlspecialchars());
            $value = I('value', '', htmlspecialchars());

            $b2c_dlytmplist = M('b2c_dlytmplist');
            $b2c_dlytmp = M('b2c_dlytmp');

            // 添加运费模板名称
            $dlytmplist_data = [
                'tmpname' => $type_name,
                'local_id' => $local_id,
            ];

            if (empty($type_id)) {

                try{
                    M()->execute('begin');

                    // 添加运费模板名称
                    $dlytmplist_return = $this->_add_dlytmplist($dlytmplist_data);

                    $this->_default_dlytmp($dlytmplist_return);

                    // 添加区域信息
                    $this->_add_dlytmp($value, $dlytmplist_return);

                    M()->execute('commit');
                    redirect(U('freight/dlytmpUpdate',['id'=>$dlytmplist_return]));
                }catch (\Exception $e){
                    M()->execute('rollback');
                    $this->error('保存失败,请重试');
                }

            }
        }
        $this->display();
    }

    /**
     * 默认运费模板
     */
    public function _default_dlytmp($dlytmplist_return){

        $b2c_dlytmp = M('b2c_dlytmp');
        $firstunit = I('firstunit', '', htmlspecialchars());
        $firstprice = I('firstprice', '', htmlspecialchars());
        $continueunit = I('continueunit', '', htmlspecialchars());
        $continueprice = I('continueprice', '', htmlspecialchars());
        $local_id = session('userInfo')['local_id'];

        $dlytmp_data = [
            'tmp_id' => $dlytmplist_return,
            'is_def' => '1',
            'qyname' => '默认运费模板',
            'firstunit' => $firstunit,
            'continueunit' => $continueunit,
            'firstprice' => $firstprice,
            'continueprice' => $continueprice,
            'local_id' => $local_id,
        ];
        $dlytmp_id = $b2c_dlytmp->add($dlytmp_data);
        if ($dlytmp_id === false) {
            throw new \Exception(false);
        }

    }

    /**
     *  添加运费模板名称
     */
    public function _add_dlytmplist($dlytmplist_data){
        $b2c_dlytmplist = M('b2c_dlytmplist');
        $dlytmplist_return = $b2c_dlytmplist->add($dlytmplist_data);
        if ($dlytmplist_return === false) {
            throw new \Exception(false);
        }
        return $dlytmplist_return;
    }

    /**
     * 添加区域信息
     */
    public function _add_dlytmp($value, $dlytmplist_return)
    {
        $local_id = session('userInfo')['local_id'];
        $b2c_dlytmp = M('b2c_dlytmp');
        if (!empty($value)) {
            foreach ($value as $v) {
                $v = explode('-', $v);
                $dlytmp_data = [
                    'tmp_id' => $dlytmplist_return,
                    'is_def' => '0',
                    'qyname' => $v[0],
                    'firstunit' => $v[1],
                    'continueunit' => $v[2],
                    'firstprice' => $v[3],
                    'continueprice' => $v[4],
//                                'area_group_id' => $area_group_id, // 地区配置的一系列参数 // DOTO这里需要省市区添加
                    'local_id' => $local_id,
                ];
                $select_dlytmp = $b2c_dlytmp->where(['id' => $v[5],'tmp_id' => $dlytmplist_return, 'is_def' => '0', 'local_id' => $local_id])->find();

                if (empty($select_dlytmp)) {
                    $dlytmp_id = $b2c_dlytmp->add($dlytmp_data);
                }
                if ($dlytmp_id === false) {
                    throw new \Exception(false);
                }
            }
        }
    }

    /**
     * 修改普通运费模板
     */
    public function dlytmpUpdate(){

        $local_id = session('userInfo')['local_id'];
        $id = I('id', '', intval());
        $b2c_dlytmplist = M('b2c_dlytmplist');
        $b2c_dlytmp = M('b2c_dlytmp');

        $dlytmplistMsg = $b2c_dlytmplist->where(['tmp_id' => $id, 'local_id' => $local_id])->find();
        $dlytmpDefaultMsg = $b2c_dlytmp->where(['tmp_id' => $id, 'local_id' => $local_id, 'is_def' => 1])->find();
        $dlytmpMsg = $b2c_dlytmp->where(['tmp_id' => $id, 'local_id' => $local_id, 'is_def' => 0])->select();

        $this->assign([
            'dlytmplistMsg' => $dlytmplistMsg,
            'dlytmpMsg' => $dlytmpMsg,
            'dlytmpDefaultMsg' => $dlytmpDefaultMsg
        ]);
        $this->display();
    }

    /**
     * 模板修改
     */
    public function dlytmpUpdatePost(){
        $tmp_id = I('tmp_id', '', intval());
        $local_id = session('userInfo')['local_id'];
        if (empty($tmp_id)) {
            //$this->error('错误');exit;
        }

        $b2c_dlytmplist = M('b2c_dlytmplist');

        // 查询模板名称
        $dlytmplistMsg = $b2c_dlytmplist->where(['tmp_id' => $tmp_id, 'local_id' => $local_id])->find();
        if (empty($dlytmplistMsg)) {
            //$this->error('错误');exit;
        }


        try{
            M()->execute('begin');

            // 修改运费模板名称
            $this->_update_dlytmplist($tmp_id);
            // 修改默认模板
            $this->_default_dlytmp_update($tmp_id);

            $this->_update_dlytmp($tmp_id);

            M()->execute('commit');

            redirect(U('freight/dlytmp'));
        }catch (\Exception $e){
            M()->execute('rollback');
            $this->error('保存失败');
        }

    }

    /**
     *  修改运费模板名称
     */
    public function _update_dlytmplist($tmp_id){
        $local_id = session('userInfo')['local_id'];
        $b2c_dlytmplist = M('b2c_dlytmplist');
        $tmpname = I('type_name', '', htmlspecialchars());
        $dlytmplist_return = $b2c_dlytmplist->where(['local_id' => $local_id, 'tmp_id' => $tmp_id,])->save(['tmpname' => $tmpname]);

        if ($dlytmplist_return === false) {
            throw new \Exception(false);
        }
        return $dlytmplist_return;
    }

    /**
     * 修改默认运费模板
     */
    public function _default_dlytmp_update($tmp_id){

        $b2c_dlytmp = M('b2c_dlytmp');
        $firstunit = I('firstunit', '', htmlspecialchars());
        $firstprice = I('firstprice', '', htmlspecialchars());
        $continueunit = I('continueunit', '', htmlspecialchars());
        $continueprice = I('continueprice', '', htmlspecialchars());
        $local_id = session('userInfo')['local_id'];

        $dlytmp_data = [
            'firstunit' => $firstunit,
            'continueunit' => $continueunit,
            'firstprice' => $firstprice,
            'continueprice' => $continueprice,
        ];
        $dlytmp_id = $b2c_dlytmp->where(['is_def' => 1, 'local_id' => $local_id, 'tmp_id' => $tmp_id,])->save($dlytmp_data);
        if ($dlytmp_id === false) {
            throw new \Exception(false);
        }

    }

    /**
     * 修改区域信息
     */
    public function _update_dlytmp($tmp_id)
    {
        $value = I('value', '', htmlspecialchars());
        $local_id = session('userInfo')['local_id'];
        $b2c_dlytmp = M('b2c_dlytmp');
        if (!empty($value)) {
            foreach ($value as $k=>$v) {
                $v = explode('-', $v);

                if (!empty($v[5])) {
                    // 修改
                    $dlytmp_data = [
                        'qyname' => $v[0],
                        'firstunit' => $v[1],
                        'firstprice' => $v[2],
                        'continueunit' => $v[3],
                        'continueprice' => $v[4],
                    ];

                    $dlytmp_return = $b2c_dlytmp->where(['id' => $v[5], 'tmp_id' => $tmp_id, 'is_def' => '0', 'local_id' => $local_id])->save($dlytmp_data);

                    if ($dlytmp_return === false) {
                        throw new \Exception(false);
                    }

                } else {
                    $this->_add_dlytmp([$value[$k]], $tmp_id);
                }


            }
        }
    }

    /**
     * 删除什么区域
     */
    public function dlytmpDelete(){
        $local_id = session('userInfo')['local_id'];
        $tmp_id = I('id', '', intval());

        M('b2c_dlytmplist')->where(['tmp_id' => $tmp_id, 'local_id' => $local_id])->delete();
        M('b2c_dlytmp')->where(['tmp_id' => $tmp_id, 'local_id' => $local_id])->delete();
        $this->success('删除完成');
    }



    /**
     * 添加区域设置
     */
    public function dlytmpAreaAdd(){
        if (IS_AJAX) {

            $id = I('post.id');
            $add = I('post.');
            unset($add['id']);
            if ($id) {

                $res = M('b2c_dlytmp')->where(['id'=>$id])->save($add);
            } else {
                $add['is_def'] = 0;
                $add['local_id'] = session('userInfo')['local_id'];
                $add['active'] = M('b2c_dlytmp')->where(['tmp_id'=>$add['tmp_id'], 'is_def'=>'1'])->getField('active');
                $res = M('b2c_dlytmp')->add($add);
            }
            if ($res !== false) {
                $res = ['status'=>true, 'message'=>'保存成功', 'data'=> $res];
            } else {
                $res = ['status'=>false, 'message'=>'保存失败', 'data'=> $res];
            }
            $this->ajaxReturn($res);
        }
        $id = I('get.id');
        $tmp_id = I('get.tmp_id', 0);
        if ($id) {
            $info = M('b2c_dlytmp')->where(array('id'=>$id))->find();
            $this->assign('info', $info);
        }
        $this->assign('tmp_id', $tmp_id);
        $this->display();
    }

    /**
     * 添加地址
     */
    public function dlytmpAddress(){
        $id = I('get.id', '');
        $index = I('get.index', 0);
        $count = M('ectools_regions_copy')->where('`p_region_id` IS NULL')->count();
        $list = [];
        if ($count) {
            $list = M('ectools_regions_copy')->field('region_id,local_name')->where('`p_region_id` IS NULL')->order('region_id asc')->select();
        }
        $ids = M('b2c_dlytmp')->where(['id'=>$id])->getField('area_id_list');
        if (!empty($ids)) {
            $ids_more = M('ectools_regions_copy')->field('region_id,local_name,p_region_id')->where(['region_id'=>['in', $ids]])->select();
            foreach ($list as &$item) {
                foreach ($ids_more as $i) {
                    if ($item['region_id'] == $i['p_region_id']) {
                        $item['is_show'] = true;
                        break;
                    }
                }
            }
        }
        $this->assign('list', $list);
        $this->assign('id', $id);
        $this->assign('index', $index);
        $this->display('dlytmpAddress2');
    }

    /**
     * 获取省下面的城市和区县
     */
    public function getChildsAddress() {
        if (!IS_AJAX || !$id = I('get.id')) {
            $this->ajaxReturn(['message'=>'错误的请求或参数缺失', 'status'=>true, 'data'=>'']);
        }
        $index_id=I('get.index_id');
        /**
        select
        b.region_id cid,b.local_name cname,b.p_region_id cpid,c.region_id vid,c.local_name vname,c.p_region_id vpid
        from sdb_ectools_regions_copy b
        LEFT JOIN sdb_ectools_regions_copy c on b.region_id=c.p_region_id
        where b.p_region_id=227
         */
        $data = M('ectools_regions_copy b')
            ->join(C('DB_PREFIX').'ectools_regions_copy c on b.region_id=c.p_region_id', 'LEFT')
            ->field('b.region_id cid,b.local_name cname,b.p_region_id cpid,c.region_id vid,c.local_name vname,c.p_region_id vpid')
            ->where('b.p_region_id='.$id)
            ->select();
        $list = [];
        $aa = [];
        $i=0;
        foreach ($data as $key => $item) {
            $list[$item['cid']]['cid'] = $item['cid'];
            $list[$item['cid']]['cname'] = $item['cname'];
            $list[$item['cid']]['cpid'] = $item['cpid'];

            $list[$item['cid']]['childs'] = [];
            $ii = [
                'vid' => $item['vid'],
                'vname' => $item['vname'],
                'vpid' => $item['vpid'],
            ];
            $aa[$item['cid']][] = $ii;
            $list[$item['cid']]['childs'] = $aa[$item['cid']];
        }
        sort($list);
        $list['length'] = count($list);
        //默认选中
        $ids = M('b2c_dlytmp')->where(['id'=>$index_id])->getField('area_id_list');
        if (!empty($ids)) {
            $ids_more = M('ectools_regions_copy')->field('region_id,local_name,p_region_id')->where(['region_id'=>['in', $ids]])->select();

            foreach ($list as &$item) {
                foreach ($ids_more as $i) {
                    if ($item['cid'] == $i['region_id']) {
                        $item['is_show'] = true;
                        break;
                    }
                }
                if ($item['childs'] && is_array($item['childs'])) {
                    foreach ($item['childs'] as &$c) {
                        foreach ($ids_more as $j) {
                            if ($c['vid'] == $j['region_id']) {
                                $c['is_show'] = true;
                                break;
                            }
                        }
                    }
                }
            }

        }
        $this->ajaxReturn(['message'=>'获取成功', 'status'=>true, 'data'=>$list]);
    }


    /**
     * 保存城市节点的修改
    array(4) {
    ["id"] => string(2) "54"
    ["first"] => array(2) {
        [0] => string(2) "21"
        [1] => string(3) "104"
    }
    ["twice"] => array(2) {
        [21] => array(1) {
            [0] => string(2) "22"
        }
        [104] => array(17) {
            [0] => string(3) "105"
            [1] => string(3) "113"
        }
    }
    ["second"] => array(18) {
        [22] => array(19) {
            [0] => string(2) "39"
            [1] => string(2) "24"
    }
     * }
     */
    public function saveAddress() {
//        dump($_POST);DIE;
        $id = I('post.id');
        $first_ids = I('post.first');
        $twice_ids = I('post.twice');
        $second_ids = I('post.second');

        $save = [];
        //得到一级城市的名称
        if (empty($first_ids)) {

            $save['areagroupname'] = '';
            $save['area_id_list'] = '';
            $save['area_group_id'] = '';
        } else {
            $ones = M('ectools_regions_copy')->where(array('region_id'=>array('in', $first_ids)))->field('local_name')->select();
            $areagroupname = join(',', array_column($ones, 'local_name'));
            if (empty($twice_ids) || empty($second_ids)) {
                $twice_ids = M('ectools_regions_copy')->where(array('p_region_id'=>array('in', $first_ids)))->getField('region_id', true);
                $second_ids = M('ectools_regions_copy')->where(array('p_region_id'=>array('in', $twice_ids)))->getField('region_id', true);
                //判断
                $this->_checkAddressAboutTemp($id, $second_ids);
                //处理数据
                $save = $this->_getAddressData($first_ids, $twice_ids, $second_ids);
            } else {
                //判断
                $this->_checkAddressAboutTemp($id, $second_ids);
                //处理数据
                $save = $this->_getAddressData($first_ids, $twice_ids, $second_ids);
            }
            $save['areagroupname'] = $areagroupname;
        }
        $res  = M('b2c_dlytmp')->where(['id'=>$id])->save($save);
        if ($res !== false) {
            $this->ajaxReturn(['status'=>true, 'message'=>'成功', 'data'=>'']);
        } else {
            $this->ajaxReturn(['status'=>false, 'message'=>'失败', 'data'=>'']);
        }
    }

    public function _getAddressData($first_ids, $twice_ids, $second_ids) {

        $all_ids = array_merge($first_ids, $twice_ids, $second_ids);
        $save['area_id_list'] = join(',', $all_ids);

        $lv2names = M('ectools_regions_copy')->where(array('region_id'=>array('in', $twice_ids)))->field('region_id,local_name')->select();
        $lv3names = M('ectools_regions_copy')->where(array('region_id'=>array('in', $second_ids)))->field('region_id,local_name,p_region_id')->select();

        foreach ($lv3names as &$val) {
            foreach ($lv2names as $v) {
                if ($v['region_id'] == $val['p_region_id']) {
                    $val['local_name'] = $v['local_name'].$val['local_name'];
                }
            }
        }
        //拼接中文地名
        $save['area_group_id'] = join(',', array_column($lv3names, 'local_name'));
        return $save;
    }

    public function _checkAddressAboutTemp($id, $second_ids) {
        //判断下 如果已经存在的模板中有了三级id 那么就抛出提示 放弃保存
        $has_ids = M()->query("select `id`,`area_id_list` from sdb_b2c_dlytmp where tmp_id = (
                    select tmp_id from sdb_b2c_dlytmp where id={$id}
                    )");
        if ($has_ids && count($has_ids) > 1) {
            foreach ($has_ids as $item) {
                if ($item['id'] == $id) {
                    continue;
                }

                if ($item['area_id_list']) {
                    $newarr = explode(',', $item['area_id_list']);
                    foreach ($newarr as $n) {
                        $exists = in_array($n, $second_ids);
                        if ($exists !== false) {
                            $this->ajaxReturn(['status'=>false, 'message'=>'同一个模板只能对一个地区进行设置', 'data'=>'']);
                        }
                    }
                }
            }
        }
    }
    /**
     * 店铺运费模板
     */
    public function dlyyctmp(){

        $local_id = session('userInfo')['local_id'];
        $m = M('b2c_dlyyctmp');

        $dlyyctmp = $m->where(['local_id' => $local_id])->order('id desc')->find();
        $store_info = M('webpos_local_store')->where(['local_id'=>$local_id])->field('myexpress,is_byself')->find();
        $dlyyctmp = array_merge($dlyyctmp, $store_info);
        if ($_POST) {
            $firstunit = I('firstunit', '', htmlspecialchars());
            $firstprice = I('firstprice', '', htmlspecialchars());
            $continueunit = I('continueunit', '', htmlspecialchars());
            $continueprice = I('continueprice', '', htmlspecialchars());
            $myexpress = I('myexpress', '', htmlspecialchars());

            $data = [
                'firstunit' => $firstunit,
                'firstprice' => $firstprice,
                'continueunit' => $continueunit,
                'continueprice' => $continueprice,
            ];
            $db = new Model();
            $db->startTrans();
            if (!empty($dlyyctmp)) {
                $res = $m->where(['id' => $dlyyctmp['id']])->save($data);
            }else {
                $data['local_id'] = $local_id;
                $res = $m->add($data);
            }
            $res2 = M('webpos_local_store')->where(['local_id'=>$local_id])->save(['myexpress'=>$myexpress]);
            if ($res !== false && $res2 !== false) {
                $db->commit();
            } else {
                $db->rollback();
            }
            $this->success('成功', '/Qgs/freight/dlyyctmp');exit;
        }

        $this->assign(['dlyyctmp' => $dlyyctmp]);
        $this->display();
    }

    public function changeStatus() {
        if (!IS_AJAX) {
            $this->error('错误的请求方式');
        }

        $tmp_id = I('get.tmp_id');
        $state = I('get.state');
        $state = $state == 'true' ? '1': '0';
        $local_id = session('userInfo')['local_id'];
        $where = ['local_id'=>$local_id, 'tmp_id'=>$tmp_id];
        if ($state) {
            $db = new Model();
            $db->startTrans();
            $res = M('b2c_dlytmp')->where(['local_id'=>$local_id])->save(['active'=>'0']);
            if ($res === false) {
                $db->rollback();
            } else {
                $res = M('b2c_dlytmp')->where($where)->save(['active'=>'1']);
                if ($res === false) {
                    $db->rollback();
                }
            }
            $db->commit();
            $this->ajaxReturn(['status'=>true, 'message'=>'成功', 'data'=>true]);
            die;
        } else {
            $res = M('b2c_dlytmp')->where($where)->save(['active'=>'0']);
        }
        if ($res !== false) {
            $this->ajaxReturn(['status'=>true, 'message'=>'成功', 'data'=>'']);
        } else {
            $this->ajaxReturn(['status'=>false, 'message'=>'失败', 'data'=>'']);
        }
    }
}